#!/usr/bin/env node

const log = console.log,
  { stdout, stdin } = require('process');
fs = require('fs'),
  path = require('path'),
  jwt = require('jsonwebtoken'),
  http = require('http'),
  { JWT_SECURITY_KEY, EXPIPES } = require('../config/security')

const processArgs = process.argv.slice(2);

const info = {
  host: '127.0.0.1',
  port: '8080',
  user: 'zs',
  pwd: 'ddd',
  token: '',
  userId: ''
}

//获取命令行参数
for (const arg of processArgs) {
  if (arg.startsWith('--')) {
    if (arg === '--help') {
      console.log("请输入, node client.js [--host=<host>] [--port=<port>] [--user=<user>] [--pwd=<pwd>]");
      process.exit();
    } else {
      const [key, value] = arg.substring(2).split('=');
      if (value) {
        info[key] = value;
      }
    }
  }
}

const dirInfo = {}

//客户端登录逻辑, 登录的请求头中不需要携带token
const data = {
  username: info.user,
  password: info.pwd
}

const basicPath = `http://${info.host}:${info.port}`

fetch(`${basicPath}/api/users/check`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then(res => res.json())
  .then(res => {
    if (res.status === 0) {
      const { id: userId, token } = res
      //存储token
      info.token = token
      info.userId = userId
      log(`登录成功 用户是${info.user} 用户的id是${info.userId}`)
      dirInfo[info.userId] = process.cwd()
      log(info)
      log(dirInfo)
      toinit()
      funstdin()
    } else {
      log(res.message)
    }
  })

const toinit = () => {
  log('初始化')
  fetch(`${basicPath}/init`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${info.token}`
    }
  })
    .then(res => res.text())
    .then(res => {
      log(res)
    })
}


const funstdin = () => {
  log('文件管理系统,请输入命令来实现功能')
  stdin.on('data', data => {
    const input = data.toString().trim();
    const arr = input.split(' ');
    const arr1 = []
    if (arr.length != 1) {
      for (let i = 1; i < arr.length; i++) arr1.push(arr[i])
    }
    if (arr1.length)
      log(arr1)
    if (cmds[arr[0]]) {
      //调用对应文件操作的方法
      cmds[arr[0]](...arr1)
    } else {
      log('命令错误,重新输入')
    }
  })
  stdin.on('end', () => {
    process.exit()
  })
}


const upload = name => {
  if (!name) {
    log('命令后需要输入具体的文件名称，请重新输入')
    return
  }
  const filePath = path.join(dirInfo[info.userId], name); // 文件路径
  if (!fs.existsSync(filePath)) {
    console.log('要上传的文件不存在，请重新输入文件名')
    return
  }
  const req = http.request(
    `${basicPath}/upload/${name}`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${info.token}`
      }
    },
    res => {
      if (res.statusCode !== 200) {
        console.error(`upload file Failed. Status code: ${res.statusCode}`);
        return;
      } else {
        res.pipe(stdout)
      }
    }
  )
  fs.createReadStream(filePath)
    .pipe(req)
}

const download = name => {
  if (!name) {
    console.log('命令后需要输入具体的文件名称，请重新输入')
    return
  }
  http.get(
    `${basicPath}/download/${name}`,
    {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${info.token}`
      }
    },
    res => {
      if (res.statusCode !== 200) {
        res.pipe(stdout)
        console.error(`Failed to download the file. Status code: ${res.statusCode}`);
        return;
      } else {
        log('下载成功')
        res.pipe(fs.createWriteStream(`./clientFiles/${name}`))
      }
    })

}

const remove = name => {
  if (!name) {
    console.log('命令后需要输入具体的文件名称，请重新输入')
    return
  }
  fetch(`${basicPath}/delete/${name}`, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${info.token}`
    }
  })
    .then(res => res.json())
    .then(res => {
      log(res.msg)
    })
}

const rename = (oldname, newname) => {
  if (!oldname || !newname) {
    log("命令需要两个参数，重新输入")
    return
  }
  const nameinfo = {
    oldName: oldname,
    newName: newname
  }
  fetch(`${basicPath}/rename`, {
    method: 'put',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${info.token}`
    },
    body: JSON.stringify(nameinfo)
  })
    .then(res => res.json())
    .then(res => {
      log(res.msg)
    })
}

const mkdir = filename => {
  if (!filename) {
    console.log('命令后需要参数, 请重新输入')
    return
  }
  const namedata = {
    name: filename
  }
  fetch(`${basicPath}/mkdir`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${info.token}`
    },
    body: JSON.stringify(namedata)
  })
    .then(res => res.json())
    .then(res => {
      log(res.msg)
    })
}

const list = () => {
  fetch(`${basicPath}/list`, {
    headers: {
      'Authorization': `Bearer ${info.token}`
    }
  })
    .then(res => res.json())
    .then(res => {
      log(res)
    })
}

const lcd = dirFile => {
  if (!dirFile) {
    console.log('命令后需要参数，请重新输入')
    return
  }
  const pathinfo = {
    name: dirFile,
    currentpath: dirInfo[info.userId]
  }
  fetch(`${basicPath}/lcd`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${info.token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(pathinfo)
  })
    .then(res => res.json())
    .then(res => {
      dirInfo[info.userId] = res.abspath
      log(dirInfo)
      log(res.msg)
    })
}

const lpwd = () => {
  log('当前的目录是：' + dirInfo[info.userId])
}

const rcd = name => {
  if (!name) {
    console.log('命令后需要参数，您输入错误，请重新输入')
    return
  }
  const pathinfo = {
    dir: name
  }
  fetch(`${basicPath}/rcd`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${info.token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(pathinfo)
  })
    .then(res => res.json())
    .then(res => {
      log(res.msg)
    })
}

const rpwd = () => {
  fetch(`${basicPath}/rpwd`, {
    headers: {
      'Authorization': `Bearer ${info.token}`,
    }
  })
    .then(res => res.text())
    .then(res => {
      log(res)
    })
}

const cmds = {
  upload,
  download,
  delete: remove,
  rename,
  mkdir,
  list,
  lcd,
  lpwd,
  rcd,
  rpwd
}